//
//  HRVViewController.swift
//  DaFit
//
//  Created by 尹琼 on 2022/6/10.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import MYModule
import Charts
import JXSegmentedView

class HRVDetailController: BaseViewController {
    
    var viewModel: HRVProvider = HRVProvider(date: Date())
    
    
    /// 是否显示right item
    public var showRightItem: Bool = true
    
                    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setNavigtaionBar()
        
    }
    
    func setNavigtaionBar() {
        
        navigation.item.title = "hrv_title".language
        
        navigation.bar.backgroundColor = UIColor.background
        if showRightItem {
            navigation.item.rightBarButtonItems = [rightBarButtonItem, historyBarButtonItem]
            
        }
        
    }
    
    override func makeUI() {
        super.makeUI()
        
        view.backgroundColor =  UIColor.darkBackground
        indicator.indicatorColor = UIColor.HRV.theme
        indicator.layer.shadowColor = UIColor.HRV.theme.cgColor
        segmentDataSource.titleNormalColor = UIColor.assist_A9A9A9
        segmentedView.dataSource = segmentDataSource
        segmentedView.indicators = [indicator]
        segmentedView.delegate = self

        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(segmentedView)
        contentView.addSubview(monthBarChartView)
        contentView.addSubview(weekBarChartView)
        contentView.addSubview(dayBarChartView)
        contentView.addSubview(explainTitleView)
        contentView.addSubview(explainView)
        contentView.addSubview(sevenTimeChartView)
        contentView.addSubview(pointView)
        

        scrollView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }

        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        segmentedView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(70)
        }
        
         dayBarChartView.snp.makeConstraints { make in
             make.top.equalTo(segmentedView.snp.bottom)
             make.leading.trailing.equalToSuperview()
         }
         
         weekBarChartView.snp.makeConstraints { make in
             make.edges.equalTo(dayBarChartView)
         }
         
         monthBarChartView.snp.makeConstraints { make in
             make.edges.equalTo(dayBarChartView)
         }
         
         
         
         pointView.snp.makeConstraints { make in
             make.leading.equalToSuperview()
             make.height.equalTo(180)
             make.width.equalTo(50)
             make.bottom.equalTo(dayBarChartView.snp.bottom).offset(20)
         }

     
         self.dayBarChartView.isHidden = false
         self.weekBarChartView.isHidden = true
         self.monthBarChartView.isHidden = true
        
        explainTitleView.snp.makeConstraints { make in
            make.top.equalTo(dayBarChartView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview()
        }
        
        explainView.snp.makeConstraints { make in
            make.top.equalTo(explainTitleView.snp.bottom)
            make.leading.trailing.equalToSuperview()
        }
        
        sevenTimeChartView.snp.makeConstraints { make in
            make.top.equalTo(explainView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        

        let config = self.setupConfig(isEmpty: true)
        sevenTimeChartView.barChartView.setConfig(config)
        sevenTimeChartView.barChartView.highlightFullBarEnabled = true
        self.sevenTimeChartView.barChartView.setBarCount(7)

     
    }
    
    override func bindViewModel() {
      super.bindViewModel()
        
        historyBarButtonItem.rx.tap.subscribe { [weak self] _ in
            guard let self = self else { return }
            
            let vc = HistoryController()
            vc.showType = .hrv
            self.navigationController?.pushViewController(vc, animated: true)
            
        }.disposed(by: rx.disposeBag)
        
        rightBarButtonItem.rx.tap.subscribe { [weak self] _ in
            guard let self = self else {return}
            let vc = CalendarController()
            vc.showType = .hrv24h
            self.navigationController?.pushViewController(vc, animated: true)
        }.disposed(by: rx.disposeBag)
        
       
        viewModel.updateData()

        viewModel.curDayChart.subscribe(onNext: { [weak self] hrvModel in
            guard let self = self, let hrvModel = hrvModel else { return }

            let date = hrvModel.date
           
            self.dayBarChartView.dateString = date.localString + " " + "unit_average".language
            self.dayBarChartView.heartAvg = hrvModel.hrvAvg

            self.dayBarChartView.barChartView.max = Double(hrvModel.chartMaxData)
            self.dayBarChartView.barChartView.min = Double(hrvModel.chartMinData)

            self.dayBarChartView.bind(to: .day,
                                      barDatas: hrvModel.chartDatas,
                                      YAxisMaxValue: hrvModel.chartMaxData,
                                      YAxisMinValue: hrvModel.chartMinData,
                                      YAxisLineCount: hrvModel.chartYAxisCount)



        }).disposed(by: rx.disposeBag)

        viewModel.weekChart.subscribe(onNext: {[weak self] hrvModel in
            
            guard let self = self, let model = hrvModel else { return }
    
            self.weekBarChartView.dateString = model.date.localweekRangeString + " " + "unit_average".language
            
            self.weekBarChartView.bind(type: .week,
                                       date: model.date,
                                       barDatas: model.chartDatas,
                                       allAvg: model.hrvAvg,
                                       YAxisMaxValue: model.chartMaxData,
                                       YAxisminValue: model.chartMinData,
                                       YAxisLineCount: model.chartYAxisCount)
            
            
        }).disposed(by: rx.disposeBag)

        viewModel.monthChart.subscribe(onNext: {[weak self] hrvModel in
            
            guard let self = self, let model = hrvModel else { return }
            
            self.monthBarChartView.dateString = model.date.localMonthRangeString + " " + "unit_average".language
            
            self.monthBarChartView.bind(type: .month,
                                        date:model.date,
                                        barDatas: model.chartDatas,
                                        allAvg: model.hrvAvg,
                                        YAxisMaxValue: model.chartMaxData,
                                        YAxisminValue: model.chartMinData,
                                        YAxisLineCount: model.chartYAxisCount)
            
        }).disposed(by: rx.disposeBag)
        

      
        pointView.rx.panGesture().when(.changed).subscribe(onNext: { [weak self] gesture in
            guard let `self` = self else { return }
            
            let point = gesture.location(in: self.view)
            
            let w = self.pointView.width / 2 - 2
            if point.x < w || point.x > kScreenWidth - w  {
                return
            }
            self.pointView.centerX = point.x
            
            let centenrPoint = CGPoint(x: point.x + self.pointView.width/2.0, y: point.y)
            let dayChartPoint = self.view.convert(centenrPoint, to: self.dayBarChartView)
            
            self.dayBarChartView.slider(dayChartPoint)
            self.weekBarChartView.slider(point)
            self.monthBarChartView.slider(point)
            
        }).disposed(by: rx.disposeBag)
        
        let panGesture = pointView.rx.panGesture().when(.ended).mapToVoid().asDriverOnErrorJustComplete()
        panGesture.delay(RxTimeInterval.seconds(3)).drive(onNext: {[weak self] _ in
            
            guard let self = self else { return }
            
            let chartPoint = CGPoint.zero
            self.dayBarChartView.slider(chartPoint)
            
            self.weekBarChartView.clearHighlight()
            self.monthBarChartView.clearHighlight()
            
            self.pointView.left = 0
            
        }).disposed(by: rx.disposeBag)
        
        
        // 7次
        let provider = SingleHRVProvider(date: viewModel.date)
        if let models = provider.trend7TimesHRVModels {
           
            let barHightLightColor = UIColor.HeartRate.theme
            let barNormalColor = UIColor.HeartRate.theme
            
            let barValues: [SevenTimeBarChartView.BarValue] = models.map {
                
                SevenTimeBarChartView.BarValue(time: $0.end, data: Double($0.hrv))
            }
            
            let config = self.setupConfig(isEmpty: false)
            let datas = barValues.map { $0.data }
            
            let xValueFormatter = DayAxisValueDateFormatter()
            xValueFormatter.axisValueArray = datas.map {
                
                if $0 == 0 {
                    return ""
                }
                
                return "\(Int($0))"
                
            }

            let barModel = SevenTimeBarChartView.BarsModel(color: barNormalColor, hightLightColor: barHightLightColor, bars: barValues, xAxisValueFormatter: xValueFormatter, xConfig: config)
            
            sevenTimeChartView.barModel = barModel
        }
        
        
    }
    

    func setupConfig(isEmpty: Bool) -> DFBarChartViewConfig {
        let config = DFBarChartViewConfig.init(
            xAxisLabelFont: Fonts.systemFont(ofSize: 10),
            xAxisLabelTextColor: isEmpty == false ? UIColor.assist_222222 : UIColor.assist_FFFFFF,
            xAxisLineColor: UIColor.HRV.theme,
            xAxisLineHeight: 1,
            highlightPerTapEnabled: true)
        return config
    }
    
    //MARK: - lazy load -

    public lazy var scrollView: ScrollView = {
        let view = ScrollView()
        view.showsVerticalScrollIndicator = false
        view.backgroundColor =  UIColor.darkBackground
        view.bounces = false
        return view
    }()

    public lazy var contentView: View = {
        let view = View()
        view.backgroundColor =  UIColor.darkBackground
        return view
    }()
    
    public lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        segmentedView.commonConfig(backgroundColor: UIColor.background)
        return segmentedView
    }()
    
    
    lazy var indicator: JXSegmentedIndicatorBackgroundView = {
        let indicator = JXSegmentedIndicatorBackgroundView()
        
        indicator.commonConfig(shadowColor: UIColor.Step.theme)
        
        return indicator
    }()

    lazy var segmentDataSource: JXSegmentedTitleDataSource = {
        let datasource = JXSegmentedTitleDataSource()
        
        datasource.commonConfig(titles: [
            "heart_rate_day_title".language,
            "heart_rate_week_title".language,
            "heart_rate_month_title".language])
        
        
        return datasource
    }()
    
  
    public lazy var dayBarChartView: HRVBarChartView = {
        let barChartView = HRVBarChartView()
        barChartView.unitLabel.text = "unit_hrv".language
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()
    
    public lazy var weekBarChartView: HeartRateWeekMonthChartView = {
        let barChartView = HeartRateWeekMonthChartView()
        barChartView.unitLabel.text = "unit_hrv".language
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()
    public lazy var monthBarChartView: HeartRateWeekMonthChartView = {
        let barChartView = HeartRateWeekMonthChartView()
        barChartView.unitLabel.text = "unit_hrv".language
        barChartView.backgroundColor = UIColor.background
        barChartView.setRoundedCorners(.bottom, radius: 18)
        return barChartView
    }()
    
  
    private lazy var pointView: DataPointView = {
        let view = DataPointView()
        view.pointColors = UIColor.HRV.assist_slider
        view.imgColor = UIColor.assist_FFFFFF
        return view
    }()
    
    private lazy var rightBarButtonItem: UIBarButtonItem = {
        let rightBarButtonItem = UIBarButtonItem()
        rightBarButtonItem.image = UIImage(named: "ic_date")
        return rightBarButtonItem
    }()
    
    public lazy var historyBarButtonItem: UIBarButtonItem = {
        let historyBarButtonItem = UIBarButtonItem()
        historyBarButtonItem.image = UIImage(named: "ic_data")
        return historyBarButtonItem
    }()
    
    private lazy var explainTitleView: BloodOxygenDetailTitleView = {
        let explainTitleView = BloodOxygenDetailTitleView()
        explainTitleView.bind(to: "hrv_about_title".language, bgColor: UIColor.assist_FFFFFF)
        explainTitleView.setRoundedCorners(.top, radius: 18)
        return explainTitleView
    }()
    
    private lazy var explainView: ExPlainView = {
        let explainView = ExPlainView()
        explainView.backgroundColor = UIColor.background
        explainView.updateData(
            textColor: UIColor.HRV.theme,
            title: "hrv_understand_data_tittle".language,
            explain: "hrv_understand_data_description_one".language + "\n\n" + "hrv_understand_data_description_two".language,
            explainTextColor: UIColor.HRV.theme.withAlphaComponent(0.8),
            bgColor: UIColor.HRV.theme)
        explainView.setRoundedCorners(.bottom, radius: 18)
        return explainView
    }()
    
    private lazy var sevenTimeChartView: SevenTimeBarChartView = {
        let chartView = SevenTimeBarChartView()
        chartView.backgroundColor = UIColor.background
        chartView.setRoundedCorners(.all, radius: 18)
        return chartView
    }()
    
}


extension HRVDetailController: JXSegmentedViewDelegate {

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
        
        self.dayBarChartView.isHidden = index != 0
        self.weekBarChartView.isHidden = index != 1
        self.monthBarChartView.isHidden = index != 2
        
    }
}
